'use strict';

const { DataTypes } = require('sequelize');
const sequelize = require('../../database/sequelize');
const User = require('./user');
const TravelPlan = require('./travel_plan');

const Budget = sequelize.define(
    'Budget',
    {
        id: {
            type: DataTypes.INTEGER.UNSIGNED,
            primaryKey: true,
            autoIncrement: true,
            comment: '预算ID',
        },
        user_id: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '所属用户ID',
        },
        travel_plan_id: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: true,
            comment: '关联旅行计划ID',
        },
        title: {
            type: DataTypes.STRING(100),
            allowNull: false,
            comment: '预算标题',
        },
        amount: {
            type: DataTypes.DECIMAL(10, 2),
            allowNull: false,
            defaultValue: 0,
            comment: '总预算金额',
        },
    },
    {
        tableName: 'budgets',
        timestamps: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        underscored: true,
    }
);

Budget.belongsTo(User, { foreignKey: 'user_id', as: 'user' });
Budget.belongsTo(TravelPlan, { foreignKey: 'travel_plan_id', as: 'plan' });

// 暴露模型以便 Expense 建立关联
module.exports = Budget;

// 初始化表与开发环境种子数据
(async () => {
    try {
        // await Budget.sync({ alter: true });

        if (process.env.NODE_ENV !== 'production') {
            const count = await Budget.count();
            if (count === 0) {
                // 默认使用第一个用户与第一个旅行计划
                const user = await User.findOne({ order: [['id', 'ASC']] });
                const plan = await TravelPlan.findOne({ order: [['id', 'ASC']] });
                const userId = user ? user.id : 1;
                const planId = plan ? plan.id : null;

                await Budget.bulkCreate([
                    {
                        user_id: userId,
                        travel_plan_id: planId,
                        title: '成都行-综合预算',
                        amount: 10000,
                    },
                    {
                        user_id: userId,
                        travel_plan_id: planId,
                        title: '成都行-餐饮专项预算',
                        amount: 3000,
                    },
                ]);
                console.log('✅ 已插入示例预算数据');
            }
        }
    } catch (e) {
        console.error('Budget 模型初始化失败:', e);
    }
})();